package cn.net.xyan.easy.webapp.base.controller;

import com.google.gwt.user.client.rpc.IncompatibleRemoteServiceException;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.RPC;
import com.google.gwt.user.server.rpc.RPCRequest;
import com.google.gwt.user.server.rpc.RPCServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zarra on 16/2/25.
 */
@Controller
@RequestMapping("/gwt")
public class GWTServiceController {

    @Autowired
    WebApplicationContext wac;

    @RequestMapping("/{service}")
    public void call(@PathVariable("service")String serviceName,
                     HttpServletRequest request,
                     HttpServletResponse response
    ) throws IOException, ServletException, SerializationException {
        String requestContext = RPCServletUtils.readContentAsGwtRpc(request);
        String responseContext;
        boolean acceptsGzipEncoding = RPCServletUtils.acceptsGzipEncoding(request);

        Object service = wac.getBean(serviceName);//rpcServiceMapperProvider.getService(serviceName);
        if (service == null)
            return;
        try {
            RPCRequest rpcRequest = RPC.decodeRequest(requestContext, service.getClass(), null);
            responseContext = RPC.invokeAndEncodeResponse(
                    service,
                    rpcRequest.getMethod(),
                    rpcRequest.getParameters(),
                    rpcRequest.getSerializationPolicy());
        }catch (IncompatibleRemoteServiceException ex) {
            responseContext = RPC.encodeResponseForFailedRequest(null, ex);
        }

        RPCServletUtils.writeResponse(request.getServletContext(),response,responseContext,acceptsGzipEncoding);

    }
}
